package adc.app.ui.wicket;

import java.util.Locale;

import org.apache.wicket.Session;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.model.LoadableDetachableModel;

public class ChangeLocaleLink extends LabeledLinkPanel {
	
	private static final long serialVersionUID = 1L;
	
	public static interface IChangeLocaleCallback {
		void onChangeLocale(AjaxRequestTarget target);
	}
	
	private IChangeLocaleCallback callback;

	public ChangeLocaleLink(String id) {
		super(id, new OtherLocaleModel());
		this.setLink(new AjaxFallbackLink<Locale>(this.getLinkId(), (OtherLocaleModel) this.getDefaultModel()) {

			private static final long serialVersionUID = 1L;

			@Override
			public void onClick(AjaxRequestTarget target) {
				Session.get().setLocale(this.getModelObject());
				if (callback != null) {
					callback.onChangeLocale(target);
				}
			}
			
		});
		
		this.getLabel().setDefaultModel(new DisplayOtherLocaleModel());
	}
	
	public final IChangeLocaleCallback getCallback() {
		return callback;
	}



	public final ChangeLocaleLink setCallback(IChangeLocaleCallback callback) {
		this.callback = callback;
		return this;
	}

	private static final class DisplayOtherLocaleModel extends LoadableDetachableModel<String> {

		private static final long serialVersionUID = 1L;

		@Override
		protected String load() {
			Locale currentLocale = Session.get().getLocale();
			if (currentLocale.getLanguage().startsWith("ro")) {
				return new Locale("en").getDisplayLanguage(new Locale("en"));
			} else {
				return new Locale("ro", "RO").getDisplayLanguage(new Locale("ro", "RO"));
			}
		}
		
	}

	private static final class OtherLocaleModel extends LoadableDetachableModel<Locale> {

		private static final long serialVersionUID = 1L;

		@Override
		public Locale load() {
			Locale currentLocale = Session.get().getLocale();
			if (currentLocale.getLanguage().startsWith("ro")) {
				return new Locale("en");
			} else {
				return new Locale("ro");
			}
		}
		
	}
	
}
